package main

import (
	"errors"
	"log"
	"time"
)

type Room struct {
	Id         int
	State      string
	OwnerId    string
	TTL        int
	Candidates []Candidate
	Games      []*Game
}

func (r *Room) removeCandidate(position int) {
	r.Candidates = removeFromSlice(r.Candidates, position)
}

func (r *Room) saveGame() {
	// 创建前先保存游戏（到文件？持久化）

}

func (r *Room) newGame(g *Game) {

	// 确认Players没有离场
	for _, p := range g.Players {
		if p.HasQuit {
			r.State = "DISMISSED"
			return
		}
	}

	// 追加新的游戏到队列
	r.Games = append([]*Game{new(Game)}, r.Games...)
	r.Games[0].State = "INIT"
	r.Games[0].Id = int(time.Now().Unix())
	r.Games[0].RoomId = r.Id

	// 玩家信息继承自上一轮游戏
	r.Games[0].Players = []Player{}
	for _, p := range g.Players {
		np := Player{}
		np.Id = p.Id
		np.Name = p.Name
		np.IsHuman = p.IsHuman
		np.BotType = p.BotType
		np.Chips = p.Chips - p.Invest + p.Profit
		r.Games[0].Players = append(r.Games[0].Players, np)
		log.Println()
	}

	// 初始化游戏
	r.Games[0].Setup()
	go r.Games[0].serve(r)

}

func (r *Room) startGame() error {
	// 房间人齐了之后创建游戏

	// 确认Candidate都还在
	for _, m := range r.Candidates {
		if m.IsHuman {
			if m.Name == "" || m.Id == "" {
				return errors.New("组队不成功")
			}
		}
	}

	// 创建游戏队列
	r.Games = []*Game{new(Game)}
	r.Games[0].State = "INIT"
	r.Games[0].Id = int(time.Now().Unix())
	r.Games[0].RoomId = r.Id

	// 初始化游戏
	r.Games[0].Initialize(r.Candidates)
	r.Games[0].Setup()
	go r.Games[0].serve(r)

	return nil
}
